package org.example.lanchain.controller;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.data.message.AiMessage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.example.lanchain.bean.QwMessage;
import org.example.lanchain.store.MongoChatMemoryStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 聊天历史记录管理控制器
 */
@Tag(name = "聊天历史管理")
@RestController
@RequestMapping("/api/chat")
@CrossOrigin(origins = "*")
public class ChatHistoryController {

    private static final Logger logger = LoggerFactory.getLogger(ChatHistoryController.class);

    @Autowired
    private MongoChatMemoryStore chatMemoryStore;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 获取聊天历史记录
     * @param memoryId 会话ID
     * @return 聊天消息列表
     */
    @Operation(summary = "获取聊天历史记录")
    @GetMapping("/history/{memoryId}")
    public ResponseEntity<List<Map<String, Object>>> getChatHistory(@PathVariable Long memoryId) {
        try {
            logger.info("获取聊天历史记录，memoryId: {}", memoryId);
            
            List<ChatMessage> messages = chatMemoryStore.getMessages(memoryId);
            List<Map<String, Object>> result = new ArrayList<>();
            
            // 用于去重的Set，记录已经添加的消息内容
            Set<String> addedMessages = new HashSet<>();
            
            for (ChatMessage message : messages) {
                Map<String, Object> msgMap = new HashMap<>();
                
                String content = "";
                boolean isUser = false;
                
                if (message instanceof UserMessage) {
                    content = ((UserMessage) message).singleText();
                    // 清理用户消息中可能残留的RAG增强信息
                    content = cleanUserMessageContent(content);
                    isUser = true;
                } else if (message instanceof AiMessage) {
                    content = ((AiMessage) message).text();
                    isUser = false;
                }
                
                // 跳过空内容的消息
                if (content == null || content.trim().isEmpty()) {
                    continue;
                }
                
                // 去重：如果是相同内容的AI消息，跳过
                String messageKey = isUser + ":" + content;
                if (addedMessages.contains(messageKey)) {
                    logger.info("跳过重复消息: {}", content.substring(0, Math.min(content.length(), 50)));
                    continue;
                }
                addedMessages.add(messageKey);
                
                msgMap.put("content", content);
                msgMap.put("isUser", isUser);
                msgMap.put("timestamp", System.currentTimeMillis()); // 可以考虑从数据库获取真实时间戳
                result.add(msgMap);
            }
            
            logger.info("成功获取 {} 条聊天记录（去重后）", result.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取聊天历史记录失败，memoryId: {}", memoryId, e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 删除聊天历史记录
     * @param memoryId 会话ID
     * @return 删除结果
     */
    @Operation(summary = "删除聊天历史记录")
    @DeleteMapping("/history/{memoryId}")
    public ResponseEntity<Boolean> deleteChatHistory(@PathVariable Long memoryId) {
        try {
            logger.info("删除聊天历史记录，memoryId: {}", memoryId);
            chatMemoryStore.deleteMessages(memoryId);
            logger.info("成功删除聊天历史记录，memoryId: {}", memoryId);
            return ResponseEntity.ok(true);
        } catch (Exception e) {
            logger.error("删除聊天历史记录失败，memoryId: {}", memoryId, e);
            return ResponseEntity.ok(false);
        }
    }

    /**
     * 获取所有会话列表
     * @return 会话列表
     */
    @Operation(summary = "获取所有会话列表")
    @GetMapping("/sessions")
    public ResponseEntity<List<Map<String, Object>>> getAllSessions() {
        try {
            logger.info("获取所有会话列表");
            
            Query query = new Query();
            List<QwMessage> qwMessages = mongoTemplate.find(query, QwMessage.class);
            
            List<Map<String, Object>> sessions = new ArrayList<>();
            for (QwMessage qwMessage : qwMessages) {
                Map<String, Object> session = new HashMap<>();
                session.put("memoryId", qwMessage.getMemoryId());
                
                // 解析消息获取最后一条消息内容作为预览
                try {
                    List<ChatMessage> messages = ChatMessageDeserializer.messagesFromJson(qwMessage.getContent());
                    if (!messages.isEmpty()) {
                        ChatMessage lastMessage = messages.get(messages.size() - 1);
                        String preview = "";
                        
                        if (lastMessage instanceof UserMessage) {
                            preview = ((UserMessage) lastMessage).singleText();
                        } else if (lastMessage instanceof AiMessage) {
                            preview = ((AiMessage) lastMessage).text();
                        }
                        
                        if (preview.length() > 50) {
                            preview = preview.substring(0, 50) + "...";
                        }
                        session.put("lastMessage", preview);
                        session.put("messageCount", messages.size());
                    } else {
                        session.put("lastMessage", "空会话");
                        session.put("messageCount", 0);
                    }
                } catch (Exception e) {
                    session.put("lastMessage", "解析失败");
                    session.put("messageCount", 0);
                }
                
                sessions.add(session);
            }
            
            logger.info("成功获取 {} 个会话", sessions.size());
            return ResponseEntity.ok(sessions);
        } catch (Exception e) {
            logger.error("获取会话列表失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 测试聊天记录存储功能
     * @param memoryId 会话ID  
     * @return 测试结果
     */
    @Operation(summary = "测试聊天记录存储")
    @PostMapping("/test/{memoryId}")
    public ResponseEntity<Map<String, Object>> testChatStorage(@PathVariable Long memoryId) {
        try {
            logger.info("测试聊天记录存储，memoryId: {}", memoryId);
            
            // 先检查是否已有记录
            List<ChatMessage> existingMessages = chatMemoryStore.getMessages(memoryId);
            logger.info("现有消息数量: {}", existingMessages.size());
            
            // 创建测试消息
            List<ChatMessage> testMessages = new ArrayList<>();
            testMessages.add(dev.langchain4j.data.message.UserMessage.from("测试用户消息"));
            testMessages.add(dev.langchain4j.data.message.AiMessage.from("测试AI回复"));
            
            // 保存测试消息
            chatMemoryStore.updateMessages(memoryId, testMessages);
            logger.info("已保存测试消息到数据库");
            
            // 重新获取验证
            List<ChatMessage> retrievedMessages = chatMemoryStore.getMessages(memoryId);
            logger.info("验证：从数据库获取到 {} 条消息", retrievedMessages.size());
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("memoryId", memoryId);
            result.put("existingMessagesCount", existingMessages.size());
            result.put("testMessagesCount", testMessages.size());
            result.put("retrievedMessagesCount", retrievedMessages.size());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("测试聊天记录存储失败，memoryId: {}", memoryId, e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("error", e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 创建新会话
     * @param assistantId 助手ID
     * @return 新会话信息
     */
    @Operation(summary = "创建新会话")
    @PostMapping("/session")
    public ResponseEntity<Map<String, Object>> createNewSession(@RequestBody Map<String, Object> request) {
        try {
            Long assistantId = request.get("assistantId") != null ? 
                Long.valueOf(request.get("assistantId").toString()) : null;
            
            // 生成新的memoryId
            Long memoryId = System.currentTimeMillis() + (long)(Math.random() * 1000);
            String sessionId = "session_" + System.currentTimeMillis() + "_" + 
                Double.toStriescesng(Math.random()).substring(2, 8);
            
            Map<String, Object> result = new HashMap<>();
            result.put("memoryId", memoryId);
            result.put("sessionId", sessionId);
            result.put("assistantId", assistantId);
            
            logger.info("创建新会话: memoryId={}, sessionId={}, assistantId={}", 
                memoryId, sessionId, assistantId);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("创建新会话失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 初始化会话打招呼语
     * @param memoryId 会话ID
     * @param request 包含欢迎语内容的请求
     * @return 初始化结果
     */
    @Operation(summary = "初始化会话打招呼语")
    @PostMapping("/init-welcome/{memoryId}")
    public ResponseEntity<Map<String, Object>> initWelcomeMessage(@PathVariable Long memoryId, 
                                                                  @RequestBody Map<String, Object> request) {
        try {
            String welcomeMessage = request.get("welcomeMessage") != null ? 
                request.get("welcomeMessage").toString() : "您好！我是您的智能客服助手，有什么可以帮助您的吗？";
            
            logger.info("初始化会话打招呼语，memoryId: {}, welcomeMessage: {}", memoryId, welcomeMessage);
            
            // 检查是否已经有消息存在
            List<ChatMessage> existingMessages = chatMemoryStore.getMessages(memoryId);
            
            // 只有在没有任何消息的情况下才添加欢迎语
            if (existingMessages.isEmpty()) {
                List<ChatMessage> welcomeMessages = new ArrayList<>();
                welcomeMessages.add(dev.langchain4j.data.message.AiMessage.from(welcomeMessage));
                
                // 保存到MongoDB
                chatMemoryStore.updateMessages(memoryId, welcomeMessages);
                logger.info("成功初始化会话打招呼语，memoryId: {}", memoryId);
            } else {
                logger.info("会话已有消息，跳过初始化打招呼语，memoryId: {}, 现有消息数: {}", memoryId, existingMessages.size());
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("memoryId", memoryId);
            result.put("welcomeMessage", welcomeMessage);
            result.put("existingMessagesCount", existingMessages.size());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("初始化会话打招呼语失败，memoryId: {}", memoryId, e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("error", e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 清理用户消息内容，移除可能的RAG增强信息
     * 
     * @param content 原始消息内容
     * @return 清理后的消息内容
     */
    private String cleanUserMessageContent(String content) {
        if (content == null) {
            return "";
        }
        
        // 移除RAG增强信息
        if (content.contains("\n\nAnswer using the following information:")) {
            content = content.split("\n\nAnswer using the following information:")[0].trim();
        }
        
        // 移除其他可能的RAG模式
        if (content.contains("\nAnswer using the following information:")) {
            content = content.split("\nAnswer using the following information:")[0].trim();
        }
        
        return content;
    }
}